<?php
/*
抖音API
*/
namespace api;
class Douyin {
    private $clientId;
    private $clientSecret;
    public $accessToken;
    private $expiresIn=0;
    private $refreshToken;
    private $refreshExpiresIn=0;
    
    public function __construct($clientId, $clientSecret) {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->accessToken = null;
        $this->expiresIn = 0;
        $this->refreshExpiresIn = 0;
        $this->refreshToken = null;
    }
    
    public function getAuthorizationUrl($redirectUri) {
        $url = 'https://open.douyin.com/platform/oauth/connect/';
        
        $params = [
            'client_key' => $this->clientId,
            'response_type' => 'code',
            'scope' => 'user_info,trial.whitelist',
            'redirect_uri' => $redirectUri,
        ];
        
        return $url . '?' . http_build_query($params);
    }
    
    public function getAccessToken($code, $redirectUri) {
        $url = 'https://open.douyin.com/oauth/access_token/';
        
        $params = [
            'client_key' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code' => $code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $redirectUri,
        ];
        
        $response = file_get_contents($url . '?' . http_build_query($params));
        $accessTokenResponse = json_decode($response, true);
        
        if ($accessTokenResponse && isset($accessTokenResponse['access_token'])) {
            $this->accessToken = $accessTokenResponse['access_token'];
            $this->expiresIn = time() + $accessTokenResponse['expires_in'];
            $this->refreshToken = $accessTokenResponse['refresh_token'];
            $this->refreshExpiresIn = time() + $accessTokenResponse['refresh_expires_in'];
        }
        
        return $accessTokenResponse;
    }
    
    public function refreshAccessToken() {
        $url = 'https://open.douyin.com/oauth/refresh_token/';
        
        $params = [
            'client_key' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'grant_type' => 'refresh_token',
            'refresh_token' => $this->refreshToken,
        ];
        
        $response = file_get_contents($url . '?' . http_build_query($params));
        $accessTokenResponse = json_decode($response, true);
        
        if ($accessTokenResponse && isset($accessTokenResponse['access_token'])) {
            $this->accessToken = $accessTokenResponse['access_token'];
            $this->expiresIn = time() + $accessTokenResponse['expires_in'];
            $this->refreshToken = $accessTokenResponse['refresh_token'];
        }
        
        return $accessTokenResponse;
    }
    
    public function searchVideosByKeyword($keyword) {
        if (!$this->accessToken || time() >= $this->expiresIn) {
            // 访问令牌过期或未获取，需要重新获取或刷新访问令牌
            // 这里可以根据你的具体逻辑来判断是重新获取还是刷新访问令牌
            // 这里以刷新访问令牌为例
            $refreshTokenResponse = $this->refreshAccessToken();
            
            if (!$refreshTokenResponse || !isset($refreshTokenResponse['access_token'])) {
                return ['error' => 'Failed to refresh access token'];
            }
        }
        
        $url = 'https://open.douyin.com/v2/search/video/';
        
        $params = [
            'access_token' => $this->accessToken,
            'keyword' => $keyword,
        ];
        
        $url .= '?' . http_build_query($params);
        
        $response = file_get_contents($url);
        
        return json_decode($response, true);
    }
}

/*
// 使用示例
$clientId = 'awc4zgtb7vf9nkym';
$clientSecret = 'bba712a2aa9399b25689aca493bc18cb';
$redirectUri = 'YOUR_REDIRECT_URI';
$keyword = '关键词';

$douyinAPI = new DouyinAPI($clientId, $clientSecret);
$authorizationUrl = $douyinAPI->getAuthorizationUrl($redirectUri);

// 将用户重定向到授权页面
header('Location: ' . $authorizationUrl);
exit;

// 在重定向的页面中获取授权码
$code = $_GET['code'];

$accessTokenResponse = $douyinAPI->getAccessToken($code, $redirectUri);

if ($accessTokenResponse && isset($accessTokenResponse['access_token'])) {
    // 成功获取访问令牌，可以进行后续操作
    $searchResults = $douyinAPI->searchVideosByKeyword($keyword);
    
    // 处理搜索结果
    if ($searchResults['data']) {
        foreach ($searchResults['data'] as $video) {
            echo '视频标题：' . $video['title'] . '<br>';
            echo '视频作者：' . $video['author']['nickname'] . '<br>';
            echo '视频描述：' . $video['desc'] . '<br>';
            echo '视频播放量：' . $video['stats']['play_count'] . '<br>';
            echo '<br>';
        }
    } else {
        echo '没有找到相关视频。';
    }
} else {
    echo '获取访问令牌失败。';
}*/
?>